//
//  YLInvestmentCertificateViewModel.m
//  YLFinanceService
//
//  Created by she1323 on 2017/10/26.
//  Copyright © 2017年 she1323. All rights reserved.
//

#import "YLInvestmentCertificateViewModel.h"
#import "WHNetworkTool.h"
#import "WHProgressHUD.h"
#import "YLAccountTool.h"
#import "YLInvestmentCertificateModel.h"
#import <YYModel.h>
@implementation YLInvestmentCertificateViewModel

- (instancetype)init
{
    if (self = [super init]) {
        [self setUp];
    }
    return self;
}

- (void)setUp
{
    
    __weak typeof(self) weakSelf = self;
    _requestCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
       
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            
            NSString *url = [NSString stringWithFormat:@"%@AppCommon/PGetCustomerVoucher", YLURL];
            
            NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:2];
            params[@"PageIndex"] = input;
            NSInteger count = 10;
            params[@"MaxResultCount"] = @(count);
            
            
            [[WHNetworkTool shareInstance] sendPostWithUrl:url header:[YLAccountTool header] params:params success:^(id responseObject) {
                if ([responseObject[@"httpCode"] integerValue] == 200) {
                    if ([input integerValue] == 1) {
                        [weakSelf.models removeAllObjects];
                    }
                    
                    NSDictionary *dict = responseObject[@"httpResult"];
                    
                    YLInvestmentCertificateItem *item = [YLInvestmentCertificateItem yy_modelWithDictionary:dict[@"item"]];
                    [weakSelf.models addObjectsFromArray:item.items];
                    
                    [subscriber sendNext:nil];
                    
                    if (item.items.count < count) {
                        [weakSelf.wh_noMoreDataSubject sendNext:nil];
                    }
                    
                } else {
                    [WHProgressHUD showError:responseObject[@"message"]];
                    [weakSelf.wh_loadDataErrorSubject sendNext:nil];
                }
                
                [subscriber sendCompleted];
                
            } fail:^(NSError *error) {
                [weakSelf.wh_loadDataErrorSubject sendNext:nil];
                [subscriber sendCompleted];
            }];
            
           
            return nil;
        }];
        
    }];
}

- (NSMutableArray *)models
{
    if (!_models) {
        _models = [NSMutableArray array];
    }
    return _models;
}

- (void)dealloc
{
    [[WHNetworkTool shareInstance] cancel];
    [WHProgressHUD dismiss];
}
@end
